/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui.gui.documents.actions;

import java.awt.event.ActionEvent;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.swing.AbstractAction;

import parser.AltaRicaParseModel;
import parser.AltaRicaParser;
import parser.AltaRicaParseNode.CycleDetectionException;

import ui.WindowManager;
import ui.gui.actions.OpenFileAction;
import ui.gui.documents.AbstractDocument;
import ui.gui.documents.AltaRicaTree;
import ui.gui.documents.AltaricaCodeEditor;
import ui.gui.documents.EditorAction;
import ui.gui.documents.toolbox.ToolboxPosition;

import common.AltaRicaModel;

/**
 *
 * @author stephane
 */
public class ActionViewAltaricaTree extends EditorAction {

    private static final long serialVersionUID = 1L;

    public ActionViewAltaricaTree(AbstractDocument document) {
        super("Generate tree from current model", document);
        putValue(AbstractAction.SMALL_ICON, new javax.swing.ImageIcon(OpenFileAction.class.getResource("/resources/generateTree.png")));
        putValue(AbstractAction.SHORT_DESCRIPTION, "Generate altarica graph from current model");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (getDocument() != null && getDocument() instanceof AltaricaCodeEditor) {
            AltaricaCodeEditor editor = (AltaricaCodeEditor) getDocument();   
        	InputStream is = new ByteArrayInputStream(editor.getText().getBytes());
            AltaRicaParseModel pmodel = AltaRicaParser.parseModel(editor.getFileName(), is);
            AltaRicaModel model = null;
            try
            {
	            model = AltaRicaModel.compileFromAST(pmodel, false);
	            if (model != null) {
	            
	            	if (editor.getTreeView() == null) {
	            		WindowManager.getInstance().addWindow(new AltaRicaTree(getDocument()), ToolboxPosition.Right);
	            	}
	            	else {
	            		WindowManager.getInstance().SelectWindow(editor.getTreeView());
	            		editor.getTreeView().refreshGraph();
	            	}
	            }
            }
            catch (CycleDetectionException exception) {
            	System.out.println(exception.getMessage());
            }
        }
    }
}
